package com.example.demo;

import com.example.demo.dao.CustomerRep;
import com.example.demo.model.Customer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}

@Configuration
@Slf4j
class initDataSource {

//	@Bean
	public CommandLineRunner commandLineRunner(CustomerRep customerRepository, ResourceLoader resourceLoader) {
		return args -> {
			// 读取类路径下的文件
			// 有时会提示找不到文件，这时刷新一下idea的maven面板
			// 生成模拟数据：https://mockaroo.com/
			Resource resource = resourceLoader.getResource("classpath:MOCK_DATA.csv");
//             Resource resource = new ClassPathResource("MOCK_DATA.csv");

			// 计时
			long start = System.currentTimeMillis();
			List<Customer> users = parseCSVFile(resource);
			log.info("保存了 Customer 的数目为: {} , 当前线程名称是：{}", users.size(), "" + Thread.currentThread().getName());

			customerRepository.saveAll(users);

			long end = System.currentTimeMillis();
			log.info("耗时: {} 毫秒.", (end - start));
			// http://localhost:9088/restapi/h2-console
			// jdbc:h2:mem:testdb
			// sa
			// 密码不用填
		};
	}

	private List<Customer> parseCSVFile(final Resource Resource) throws Exception {
		final List<Customer> users = new ArrayList<>();
		try {
			// jdk7的try资源句式
			try (final BufferedReader br = new BufferedReader(new InputStreamReader(Resource.getInputStream()))) {
				// jdk8的Stream遍历 输入流的行
				br.lines().forEach(line -> {
					final String[] data = line.split(",");
					final Customer user = new Customer();
					// data[0]是id，不需要设置。
					user.setName(data[1]);
					user.setDateOfBirth(LocalDate.parse(data[2]));// 字符串 转 Localdate
					user.setPhoneNumber(data[3]);
					users.add(user);
				});

				return users;
			}
		} catch (final IOException e) {
			log.error("转换 CSV file 失败 {0}", e);
			throw new Exception("转换 CSV file 失败{}", e);
		}
	}
}
